
//   Texture.cpp, 7.2.07, pm-n.


#include "Texture.h"
#include "Image.h"
#include "Utilities.h"
#include <iostream>

Texture::Texture( char *rgb_bmp )
{
	reportGLError(" in Texture constructor 1", __FILE__, __LINE__);
	unsigned long  sizeX, sizeY;

	im = new Image( rgb_bmp );


	channels = 3;

	glGenTextures( 1, &texture_id );
	reportGLError(" in Texture constructor 2", __FILE__, __LINE__);
	glBindTexture( GL_TEXTURE_2D, texture_id );

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	im->get_sizes( sizeX, sizeY );
	glTexImage2D( GL_TEXTURE_2D, 0, 3, sizeX, sizeY, 0, 
		GL_RGB, GL_UNSIGNED_BYTE, im->access_pixel() );
	reportGLError(" in Texture constructor 3", __FILE__, __LINE__);
}


Texture::Texture(char *rgb_bmp, char *bw_bmp )
{
	unsigned long  sizeX, sizeY;

	im= new Image( rgb_bmp, bw_bmp );

	channels = 4;

	glGenTextures( 1, &texture_id );
	glBindTexture( GL_TEXTURE_2D, texture_id );

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	im->get_sizes( sizeX, sizeY );
	glTexImage2D( GL_TEXTURE_2D, 0, 4, sizeX, sizeY, 0, 
		GL_RGBA, GL_UNSIGNED_BYTE, im->access_pixel() );
}

Texture::Texture(int h, int w, float * data) 
{
	channels = 4;

	glGenTextures( 1, &texture_id );
	glBindTexture( GL_TEXTURE_2D, texture_id );

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	glTexImage2D( GL_TEXTURE_2D, 0, 4, w, h, 0, 
		GL_RGBA, GL_FLOAT, data );
}

void  Texture::bind()
{

	//unsigned long  sizeX, sizeY;
	//if(channels==3) {
	//	glBindTexture( GL_TEXTURE_2D, texture_id );

	//	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	//	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	//	im->get_sizes( sizeX, sizeY );
	//	glTexImage2D( GL_TEXTURE_2D, 0, 3, sizeX, sizeY, 0, 
	//		GL_RGB, GL_UNSIGNED_BYTE, im->access_pixel() );
	//}
	//else {
	//	glBindTexture( GL_TEXTURE_2D, texture_id );

	//	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	//	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	//	im->get_sizes( sizeX, sizeY );
	//	glTexImage2D( GL_TEXTURE_2D, 0, 4, sizeX, sizeY, 0, 
	//		GL_RGBA, GL_UNSIGNED_BYTE, im->access_pixel() );
	//}
	glBindTexture( GL_TEXTURE_2D, texture_id );
}

void Texture::draw() 
{
	glPushAttrib(GL_ENABLE_BIT);

	this->bind();
	//glEnable(GL_BLEND);
	glColor3f(1.0,1.0,1.0);

	glBegin(GL_QUADS);

	glNormal3f(0.0,0.0,1.0);

	glTexCoord2f(0.0,0.0);  
	glVertex3f(0.0,0.0,0.0);

	glTexCoord2f(1.0,0.0);  
	glVertex3f(1.0,0.0,0.0);

	glTexCoord2f(1.0,1.0);  
	glVertex3f(1.0,1.0,0.0);

	glTexCoord2f(0.0,1.0);  
	glVertex3f(0.0,1.0,0.0);

	glEnd();

	glPopAttrib();
}


int   Texture::getChannels()
{
	return channels;
}

